package thread;

/**
 * 演示多线程并发安全问题
 * 当多个线程并发访问同一临界资源
 */
public class SyncDemo1 {
    public static boolean success1 = false;//表示第一个人是否取款成功
    public static boolean success2 = true;//表示第二个人是否取款成功

    public static void main(String[] args) {

        Bank bank = new Bank();
        int sum = 0;
        while (true) {
            sum++;
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };

            Thread t2 = new Thread() {
                @Override
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            try {
                Thread.sleep(1);//让主线程阻塞1秒钟,目的是等上面两个线程执行完
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(success1);
            System.out.println(success2);
            if (success1&&success2){
                System.out.println("同时取款成功!出现了并发安全问题!");
                System.out.println("执行了"+sum+"次成功了");
                break;
            }else {
                bank.saveMoney(20000);
                success1 = false;
                success2 = false;
            }
        }
    }
}
